package com.chaoyer.cynet.access.handler.websocket;


import com.chaoyer.cynet.access.handler.http.HttpServerHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebSocketHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private WebSocketServerHandshaker handshaker;


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            ctx.pipeline().remove(HttpServerHandler.class);
            // group.writeAndFlush("");
            logger.info("Client: " + ctx.channel().remoteAddress() + "加入");
            group.add(ctx.channel());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 判断是否是关闭链路的指令
        if (msg instanceof CloseWebSocketFrame) {
            logger.info("CloseWebSocketFrame");
            handshaker.close(ctx.channel(), ((CloseWebSocketFrame) msg).retain());
            return;
        }
        // 判断是否是Ping消息
        if (msg instanceof PingWebSocketFrame) {
            logger.info("PingWebSocketFrame");

            ctx.channel().write(new PongWebSocketFrame(((PingWebSocketFrame) msg).content().retain()));
            return;
        }
        // 当前只支持文本消息，不支持二进制消息
        if (!(msg instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException("当前只支持文本消息，不支持二进制消息");
        }
        logger.info("TextWebSocketFrame");

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("WebSocket异常", cause);
        ctx.close();
        logger.info("  注销");
    }

}
